package com.stuManager.util;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

//处理cookie的一些工具方法
public class CookiesUtil {

    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap =  ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        }
        else {
            return null;
        }
    }

    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int time) {
        System.out.println("设置cookie：" + name + "为" + value);
//        cookie.setPath("/");
        if (value != null) {
            value = URLEncoder.encode(value, StandardCharsets.UTF_8);
        }
        Cookie cookie = new Cookie(name, value);
        System.out.println("encode？");
        cookie.setMaxAge(time);
        System.out.println("设置time为" + time);
        response.addCookie(cookie);
        System.out.println("设置cookie完毕");
        return response;
    }

    public  static HttpServletResponse deleteCookie(HttpServletRequest request, HttpServletResponse response) {
        try {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                setCookie(response, cookie.getName(), cookie.getValue(), 0);
                System.out.println("delete cookie :" + cookie.getName());
            }
        }
        catch (Exception e) {
            System.out.println("删除cookie失败" + e.getMessage());
        }
        return response;
    }
}
